<!--
    自定义搜索框，具有延迟查询机制，每次输入都会重新刷新延迟查询的时间，默认延迟2秒

    用法：<f7-custom-searchbar :delay="2000" search-container=".search-list" search-in=".item-text" @search="searchQuery" v-model="search.projectName"></f7-custom-searchbar>

    备注：delay, search-in, search-container 可选，有默认值
        v-model，必填，表示输入框输入的值和search.projectName绑定，请按实际查询参数传进来
        searchQuery，必填，通常为controller.js里定义好的searchQuery查询方法
 -->
<template id="f7-custom-searchbar">
  <f7-searchbar
    :custom-search="true"
    @searchbar:search="customSearch"
    @searchbar:clear="clear"
    @searchbar:disable="disable"
    @input="emitInput"
    :search-container="searchContainer"
    :search-in="searchIn"
    :placeholder="placeholder"
    :disableButtonText="disableButtonText"
    :value="value"
  ></f7-searchbar>
</template>
<script>
export default {
  data: function() {
    return {
      timeout: null
    };
  },
  props: {
    placeholder: {
      type: String,
      default: '搜索'
    },
    disableButtonText: {
      type: String,
      default: '取消'
    },
    value: {
      // 声明value属性
      type: String,
      default: ""
    },
    searchContainer: {
      type: String,
      default: ".search-list"
    },
    searchIn: {
      type: String,
      default: ".item-text"
    },
    delay: {
      // 延迟多少时间触发查询
      type: Number,
      default: 2000
    }
  },
  methods: {
    emitInput($event) {
      // 触发input事件，传入新值
      this.$emit("input", $event.target.value);
    },
    customSearch(searchbar, query, previousQuery) {
      let self = this;
      if (self.timeout) {
        window.clearTimeout(self.timeout);
      }
      // 刷新计时
      self.timeout = window.setTimeout(() => {
        self.timeout = null;
        // 触发自定义search事件，页面上调用@search="your function"
        self.$emit("search");
      }, self.delay);
    },
    clear(searchbar, previousQuery) {
      // 触发input事件，传入空值
      this.$emit("input", "");
    },
    disable(searchbar) {
      // 触发input事件，传入空值
      this.$emit("input", "");
    }
  }
};
</script>
